package com.homework.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.homework.dto.HomeworkCreateDTO;
import com.homework.dto.HomeworkDetailDTO;
import com.homework.dto.Result;
import com.homework.entity.DailyHomework;
import com.homework.entity.Homework;
import com.homework.entity.HomeworkDetail;
import com.homework.entity.Student;
import com.homework.mapper.DailyHomeworkMapper;
import com.homework.mapper.HomeworkDetailMapper;
import com.homework.mapper.HomeworkMapper;
import com.homework.mapper.StudentMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class HomeworkService {

    private final HomeworkMapper homeworkMapper;
    private final HomeworkDetailMapper homeworkDetailMapper;
    private final DailyHomeworkMapper dailyHomeworkMapper;
    private final StudentMapper studentMapper;

    /**
     * 创建作业
     */
    @Transactional
    public Result<String> createHomework(HomeworkCreateDTO dto) {
        // 验证学生是否存在
        Student student = studentMapper.selectById(dto.getStudentId());
        if (student == null) {
            return Result.error("学生不存在，请先创建学生信息");
        }

        // 检查时间冲突（只检查完全相同的时间）
        List<Homework> conflictingHomework = homeworkMapper.findConflictingHomework(
                dto.getStudentId(), dto.getStartTime(), dto.getEndTime(), null);
        if (!conflictingHomework.isEmpty()) {
            return Result.error("该时间段已存在相同的作业，请选择不同的时间");
        }

        // 自动添加日常作业
        List<HomeworkDetailDTO> allDetails = new ArrayList<>();
        if (dto.getDetails() != null) {
            allDetails.addAll(dto.getDetails());
        }

        // 获取启用的日常作业
        List<DailyHomework> dailyHomeworks = dailyHomeworkMapper.selectList(
            new LambdaQueryWrapper<DailyHomework>()
                .eq(DailyHomework::getIsActive, true)
                .orderByAsc(DailyHomework::getSequenceOrder)
        );

        // 将日常作业转换为作业明细
        for (DailyHomework daily : dailyHomeworks) {
            HomeworkDetailDTO detail = new HomeworkDetailDTO();
            detail.setContent(daily.getContent());
            detail.setIsRequired(daily.getIsRequired());
            allDetails.add(detail);
        }

        // 计算必须完成的项目数
        int requiredCount = (int) allDetails.stream()
            .mapToInt(detail -> detail.getIsRequired() ? 1 : 0)
            .sum();

        // 创建作业 - 确保时间使用正确的时区
        Homework homework = new Homework();
        homework.setTitle(dto.getTitle());
        homework.setStudentId(dto.getStudentId());

        // 处理时间，确保使用Asia/Shanghai时区
        ZoneId shanghaiZone = ZoneId.of("Asia/Shanghai");
        LocalDateTime startTime = dto.getStartTime();
        LocalDateTime endTime = dto.getEndTime();

        // 如果传入的时间已经是LocalDateTime，直接使用
        // 在配置文件中已设置时区，这样应该能正确处理
        homework.setStartTime(startTime);
        homework.setEndTime(endTime);

        homework.setStatus(0); // 未开始
        homework.setTotalItems(allDetails.size());
        homework.setCompletedItems(0);
        homework.setRequiredCompletedItems(0);

        homeworkMapper.insert(homework);

        // 创建作业明细
        for (int i = 0; i < allDetails.size(); i++) {
            HomeworkDetail detail = new HomeworkDetail();
            detail.setHomeworkId(homework.getId());
            detail.setContent(allDetails.get(i).getContent());
            detail.setSequenceOrder(i + 1);
            detail.setIsRequired(allDetails.get(i).getIsRequired());
            detail.setIsCompleted(false);
            homeworkDetailMapper.insert(detail);
        }

        return Result.success("作业创建成功");
    }

    /**
     * 更新作业
     */
    @Transactional
    public Result<String> updateHomework(HomeworkCreateDTO dto) {
        // 获取原作业信息
        Homework originalHomework = homeworkMapper.selectById(dto.getId());
        if (originalHomework == null) {
            return Result.error("作业不存在");
        }

        // 检查作业状态 - 已完成的作业不能修改明细
        if (originalHomework.getStatus() == 2) {
            return Result.error("已完成的作业不能修改");
        }

        // 检查时间冲突
        List<Homework> conflictingHomework = homeworkMapper.findConflictingHomework(
                dto.getStudentId(), dto.getStartTime(), dto.getEndTime(), dto.getId());
        if (!conflictingHomework.isEmpty()) {
            return Result.error("你当前的作业安排与 " + conflictingHomework.get(0).getTitle() + " 的作业时间有冲突，请检查后再配置");
        }

        // 获取原有的作业明细
        List<HomeworkDetail> originalDetails = homeworkDetailMapper.selectList(
            new LambdaQueryWrapper<HomeworkDetail>()
                .eq(HomeworkDetail::getHomeworkId, dto.getId())
        );

        // 更新作业基本信息
        Homework homework = new Homework();
        homework.setId(dto.getId());
        homework.setTitle(dto.getTitle());
        homework.setStartTime(dto.getStartTime());
        homework.setEndTime(dto.getEndTime());
        homework.setTotalItems(dto.getDetails().size());

        // 保留原有的完成进度
        homework.setCompletedItems(originalHomework.getCompletedItems());
        homework.setRequiredCompletedItems(originalHomework.getRequiredCompletedItems());
        homework.setStatus(originalHomework.getStatus());

        homeworkMapper.updateById(homework);

        // 如果作业尚未开始，可以完全重新创建明细
        if (originalHomework.getStatus() == 0) {
            // 删除原有明细
            homeworkDetailMapper.delete(
                    new LambdaQueryWrapper<HomeworkDetail>()
                            .eq(HomeworkDetail::getHomeworkId, dto.getId())
            );

            // 重新创建作业明细
            for (int i = 0; i < dto.getDetails().size(); i++) {
                HomeworkDetail detail = new HomeworkDetail();
                detail.setHomeworkId(dto.getId());
                detail.setContent(dto.getDetails().get(i).getContent());
                detail.setIsRequired(dto.getDetails().get(i).getIsRequired());
                detail.setSequenceOrder(i + 1);
                detail.setIsCompleted(false);
                homeworkDetailMapper.insert(detail);
            }
        } else {
            // 作业已开始，需要智能合并明细，保留已完成项目

            // 创建内容到原有明细的映射
            java.util.Map<String, HomeworkDetail> contentToDetail = new java.util.HashMap<>();
            for (HomeworkDetail detail : originalDetails) {
                contentToDetail.put(detail.getContent(), detail);
            }

            // 先删除未完成的原有明细
            homeworkDetailMapper.delete(
                    new LambdaQueryWrapper<HomeworkDetail>()
                            .eq(HomeworkDetail::getHomeworkId, dto.getId())
                            .eq(HomeworkDetail::getIsCompleted, false)
            );

            // 重新创建作业明细，保留已完成的
            for (int i = 0; i < dto.getDetails().size(); i++) {
                String content = dto.getDetails().get(i).getContent();
                HomeworkDetail existingCompletedDetail = contentToDetail.get(content);

                if (existingCompletedDetail != null && existingCompletedDetail.getIsCompleted()) {
                    // 保留已完成的明细，只更新序号和必须性
                    existingCompletedDetail.setSequenceOrder(i + 1);
                    existingCompletedDetail.setIsRequired(dto.getDetails().get(i).getIsRequired());
                    homeworkDetailMapper.updateById(existingCompletedDetail);
                } else {
                    // 创建新的明细
                    HomeworkDetail detail = new HomeworkDetail();
                    detail.setHomeworkId(dto.getId());
                    detail.setContent(content);
                    detail.setIsRequired(dto.getDetails().get(i).getIsRequired());
                    detail.setSequenceOrder(i + 1);
                    detail.setIsCompleted(false);
                    homeworkDetailMapper.insert(detail);
                }
            }

            // 重新计算完成项目数
            List<HomeworkDetail> newDetails = homeworkDetailMapper.selectList(
                new LambdaQueryWrapper<HomeworkDetail>()
                    .eq(HomeworkDetail::getHomeworkId, dto.getId())
            );

            int completedCount = (int) newDetails.stream()
                .mapToInt(d -> d.getIsCompleted() ? 1 : 0)
                .sum();

            int requiredCompletedCount = (int) newDetails.stream()
                .filter(d -> d.getIsRequired() && d.getIsCompleted())
                .count();

            homework.setCompletedItems(completedCount);
            homework.setRequiredCompletedItems(requiredCompletedCount);
            homeworkMapper.updateById(homework);
        }

        return Result.success("作业更新成功");
    }

    /**
     * 删除作业
     */
    @Transactional
    public Result<String> deleteHomework(Long id) {
        // 删除作业明细
        homeworkDetailMapper.delete(
                new LambdaQueryWrapper<HomeworkDetail>()
                        .eq(HomeworkDetail::getHomeworkId, id)
        );

        // 删除作业
        homeworkMapper.deleteById(id);

        return Result.success("作业删除成功");
    }

    /**
     * 获取当前作业（最早的）
     */
    public Result<Homework> getCurrentHomework(Long studentId) {
        Homework homework = homeworkMapper.findCurrentHomework(studentId, LocalDateTime.now());
        if (homework == null) {
            return Result.error("当前没有作业");
        }
        return Result.success(homework);
    }

    /**
     * 获取所有当前作业
     */
    public Result<List<Homework>> getAllCurrentHomework(Long studentId) {
        List<Homework> homeworks = homeworkMapper.findAllCurrentHomework(studentId, LocalDateTime.now());
        return Result.success(homeworks);
    }

    /**
     * 开始作业
     */
    @Transactional
    public Result<String> startHomework(Long id) {
        Homework homework = homeworkMapper.selectById(id);
        if (homework == null) {
            return Result.error("作业不存在");
        }

        homework.setStatus(1); // 进行中
        homework.setActualStartTime(LocalDateTime.now()); // 现在使用配置的时区
        homeworkMapper.updateById(homework);

        return Result.success("作业已开始");
    }

    /**
     * 完成作业项
     */
    @Transactional
    public Result<String> completeHomeworkDetail(Long detailId) {
        HomeworkDetail detail = homeworkDetailMapper.selectById(detailId);
        if (detail == null) {
            return Result.error("作业项不存在");
        }

        if (detail.getIsCompleted()) {
            return Result.error("作业项已完成");
        }

        // 更新作业项状态
        detail.setIsCompleted(true);
        detail.setCompletedTime(LocalDateTime.now()); // 现在使用配置的时区
        homeworkDetailMapper.updateById(detail);

        // 更新作业总进度
        Homework homework = homeworkMapper.selectById(detail.getHomeworkId());
        homework.setCompletedItems(homework.getCompletedItems() + 1);

        // 如果是必须完成的项目，增加必须完成计数
        if (detail.getIsRequired()) {
            homework.setRequiredCompletedItems(homework.getRequiredCompletedItems() + 1);
        }

        // 检查是否所有必须作业都完成
        List<HomeworkDetail> allDetails = homeworkDetailMapper.selectList(
            new LambdaQueryWrapper<HomeworkDetail>()
                .eq(HomeworkDetail::getHomeworkId, detail.getHomeworkId())
        );

        int totalRequired = (int) allDetails.stream()
            .mapToInt(d -> d.getIsRequired() ? 1 : 0)
            .sum();

        // 检查是否所有作业（包括非必须）都完成
        int totalCompleted = (int) allDetails.stream()
            .mapToInt(d -> d.getIsCompleted() ? 1 : 0)
            .sum();

        // 只有当所有作业都完成时才标记为已完成
        if (totalCompleted == allDetails.size()) {
            homework.setStatus(2); // 已完成
            homework.setActualEndTime(LocalDateTime.now()); // 现在使用配置的时区
        }
        // 如果所有必须作业完成但还有非必须作业未完成，保持状态为1（进行中）

        homeworkMapper.updateById(homework);

        return Result.success("作业项已完成");
    }

    /**
     * 动态添加作业项
     */
    @Transactional
    public Result<String> addHomeworkDetail(Long homeworkId, HomeworkDetailDTO dto) {
        // 检查作业是否存在
        Homework homework = homeworkMapper.selectById(homeworkId);
        if (homework == null) {
            return Result.error("作业不存在");
        }

        // 检查作业状态 - 已完成的作业不能添加新项
        if (homework.getStatus() == 2) {
            return Result.error("已完成的作业不能添加新的作业项");
        }

        // 获取当前最大序号
        List<HomeworkDetail> existingDetails = homeworkDetailMapper.selectList(
            new LambdaQueryWrapper<HomeworkDetail>()
                .eq(HomeworkDetail::getHomeworkId, homeworkId)
        );

        int maxOrder = existingDetails.stream()
            .mapToInt(HomeworkDetail::getSequenceOrder)
            .max()
            .orElse(0);

        // 创建新的作业明细
        HomeworkDetail newDetail = new HomeworkDetail();
        newDetail.setHomeworkId(homeworkId);
        newDetail.setContent(dto.getContent());
        newDetail.setSequenceOrder(maxOrder + 1);
        newDetail.setIsRequired(dto.getIsRequired() != null ? dto.getIsRequired() : true);
        newDetail.setIsCompleted(false);

        homeworkDetailMapper.insert(newDetail);

        // 更新作业的总项目数
        homework.setTotalItems(homework.getTotalItems() + 1);
        homeworkMapper.updateById(homework);

        return Result.success("作业项添加成功");
    }

    /**
     * 删除未完成作业项
     */
    @Transactional
    public Result<String> deleteHomeworkDetail(Long homeworkId, Long detailId) {
        // 检查作业是否存在
        Homework homework = homeworkMapper.selectById(homeworkId);
        if (homework == null) {
            return Result.error("作业不存在");
        }

        // 检查作业项是否存在
        HomeworkDetail detail = homeworkDetailMapper.selectById(detailId);
        if (detail == null || !detail.getHomeworkId().equals(homeworkId)) {
            return Result.error("作业项不存在");
        }

        // 检查作业项是否已完成 - 已完成的项不能删除
        if (detail.getIsCompleted()) {
            return Result.error("已完成的作业项不能删除");
        }

        // 检查作业状态 - 已完成的作业不能删除项目
        if (homework.getStatus() == 2) {
            return Result.error("已完成的作业不能删除作业项");
        }

        // 删除作业项
        homeworkDetailMapper.deleteById(detailId);

        // 更新作业的总项目数
        homework.setTotalItems(homework.getTotalItems() - 1);

        // 删除后重新计算必须完成的项目数
        // 获取删除后的所有作业明细
        List<HomeworkDetail> remainingDetails = homeworkDetailMapper.selectList(
            new LambdaQueryWrapper<HomeworkDetail>()
                .eq(HomeworkDetail::getHomeworkId, homeworkId)
        );

        // 重新计算已完成的必须项目数
        int newRequiredCompletedCount = (int) remainingDetails.stream()
            .filter(d -> d.getIsRequired() && d.getIsCompleted())
            .count();

        homework.setRequiredCompletedItems(newRequiredCompletedCount);

        homeworkMapper.updateById(homework);

        return Result.success("作业项删除成功");
    }

    /**
     * 修改作业项内容
     */
    @Transactional
    public Result<String> updateHomeworkDetail(Long homeworkId, Long detailId, HomeworkDetailDTO dto) {
        // 检查作业是否存在
        Homework homework = homeworkMapper.selectById(homeworkId);
        if (homework == null) {
            return Result.error("作业不存在");
        }

        // 检查作业项是否存在
        HomeworkDetail detail = homeworkDetailMapper.selectById(detailId);
        if (detail == null || !detail.getHomeworkId().equals(homeworkId)) {
            return Result.error("作业项不存在");
        }

        // 检查作业项是否已完成 - 已完成的项不能修改内容
        if (detail.getIsCompleted()) {
            return Result.error("已完成的作业项不能修改内容");
        }

        // 检查作业状态 - 已完成的作业不能修改项目
        if (homework.getStatus() == 2) {
            return Result.error("已完成的作业不能修改作业项");
        }

        // 更新作业项内容
        detail.setContent(dto.getContent());
        if (dto.getIsRequired() != null) {
            // 如果必须性发生变化，需要更新作业的必须完成计数
            boolean oldRequired = detail.getIsRequired();
            boolean newRequired = dto.getIsRequired();

            if (oldRequired && !newRequired && detail.getIsCompleted()) {
                // 从必须变为非必须，且已完成，减少必须完成计数
                homework.setRequiredCompletedItems(homework.getRequiredCompletedItems() - 1);
            } else if (!oldRequired && newRequired) {
                // 从非必须变为必须
                if (detail.getIsCompleted()) {
                    // 如果已完成，增加必须完成计数
                    homework.setRequiredCompletedItems(homework.getRequiredCompletedItems() + 1);
                }
            }

            detail.setIsRequired(newRequired);
        }

        homeworkDetailMapper.updateById(detail);
        homeworkMapper.updateById(homework);

        return Result.success("作业项修改成功");
    }

    /**
     * 调整作业项必须/非必须属性
     */
    @Transactional
    public Result<String> updateHomeworkDetailRequired(Long homeworkId, Long detailId, Boolean isRequired) {
        // 检查作业是否存在
        Homework homework = homeworkMapper.selectById(homeworkId);
        if (homework == null) {
            return Result.error("作业不存在");
        }

        // 检查作业项是否存在
        HomeworkDetail detail = homeworkDetailMapper.selectById(detailId);
        if (detail == null || !detail.getHomeworkId().equals(homeworkId)) {
            return Result.error("作业项不存在");
        }

        // 检查作业状态 - 已完成的作业不能修改项目属性
        if (homework.getStatus() == 2) {
            return Result.error("已完成的作业不能修改作业项属性");
        }

        // 如果必须性发生变化，需要更新作业的必须完成计数
        boolean oldRequired = detail.getIsRequired();

        if (oldRequired && !isRequired && detail.getIsCompleted()) {
            // 从必须变为非必须，且已完成，减少必须完成计数
            homework.setRequiredCompletedItems(homework.getRequiredCompletedItems() - 1);
        } else if (!oldRequired && isRequired) {
            // 从非必须变为必须
            if (detail.getIsCompleted()) {
                // 如果已完成，增加必须完成计数
                homework.setRequiredCompletedItems(homework.getRequiredCompletedItems() + 1);
            }
        }

        // 更新作业项
        detail.setIsRequired(isRequired);
        homeworkDetailMapper.updateById(detail);
        homeworkMapper.updateById(homework);

        return Result.success("作业项属性修改成功");
    }

    /**
     * 生成默认作业标题
     */
    public static String generateDefaultTitle(LocalDateTime date) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return date.format(formatter) + "家庭作业";
    }
}